use std::{
    default,
    fs::File,
    net::SocketAddr,
    path::{Path, PathBuf},
    time::Duration,
};

use anyhow::Result;
use embedding_model::EmbeddingModelConfig;
use log::error;
use serde::{Deserialize, Serialize};
use vsse::SearchConfig;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub addr: String,
    pub cache_dur: Duration,
    pub default_search_config: SearchConfig,
    pub embedding_model_config: embedding_model::EmbeddingModelConfig,
    pub content_store_path: PathBuf,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            addr: "0.0.0.0:7749".into(),
            default_search_config: SearchConfig::default(),
            content_store_path: "../vsse/materials/contentstore.json".into(),
            cache_dur: Duration::new(300, 0),
            embedding_model_config: EmbeddingModelConfig {
                path: "../embd/model/text2vec-base-chinese_safetensors".into(),
                ..EmbeddingModelConfig::default()
            },
        }
    }
}
impl Config {
    pub fn from_yaml_file<P>(path: P) -> Result<Self>
    where
        P: AsRef<Path>,
    {
        let rdr = File::open(path.as_ref()).map_err(|e| {
            error!(
                "Failed to open file at : {:?} . Error : {}.",
                path.as_ref(),
                e
            );
            e
        })?;
        let config: Config = serde_yaml::from_reader(rdr).map_err(|e| {
            error!(
                "Failed to read yaml file at : {:?} . Error : {}.",
                path.as_ref(),
                e
            );
            e
        })?;
        Ok(config)
    }
    pub fn save_yaml_file<P>(&self, path: P) -> Result<()>
    where
        P: AsRef<Path>,
    {
        let mut wtr = File::create(path.as_ref()).map_err(|e| {
            error!(
                "Failed to create file ar {:?} . Error : {}",
                path.as_ref(),
                e
            );
            e
        })?;
        serde_yaml::to_writer(wtr, self).map_err(|e| {
            error!(
                "Failed to write yaml file at {:?} . Error : {}",
                path.as_ref(),
                e
            );
            e
        })?;
        Ok(())
    }
}
